﻿
using AppFramework.Logger;
using Automation.BDaq;
using PerpheralDevice.Units;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace PerpheralDevice.Advantech {
    public class PCI1758UDI : PerpDevIO {

        private readonly int mfDiCount = 64;
        private readonly string _mfDeviceInformation = "PCI-1758UDI,BID#0";
        private readonly InstantDiCtrl _InstantDiCtrl = new ();
        private readonly ILogger miLogger;
        public PCI1758UDI(string devID, string devName, string devParamSerialized) : base() {
            this.PerpDevID = devID;
            this.PerpDevName = devName;
            this.IsMocking = !this.Initialize();
            this.InitializeUnitList();
        }

        protected override bool Initialize() {
            try {
                _InstantDiCtrl.SelectedDevice = new DeviceInformation(this._mfDeviceInformation);

                for (int i = 0; i < _InstantDiCtrl.DiintChannels.Count(); i++) {
                    _InstantDiCtrl.DiintChannels[i].Enabled = true;
                }
                this._InstantDiCtrl.Interrupt += (sender, e) => {
                    this.Unit<SwitchRO>().FirstOrDefault(it => e.SrcNum.ToString().Equals(it.UnitID))?.View();
                };
                this._InstantDiCtrl.SnapStart();
            } catch (Exception ex) {               
                this.miLogger?.Error($"{this.GetType().FullName}({this._mfDeviceInformation})板卡初始化失败", ex);
                return false;
            }
            
            return true;
        }

        protected override void InitializeUnitList() {
            this.mfPerpDevUnitList.Clear();
            for (int i = 0; i < mfDiCount; i++) {
                this.mfPerpDevUnitList.Add(new AdvantechSwitchRO(this, _InstantDiCtrl, i));
            }

            #region 轮询 IO

            this.mfPollingTask = Task.Factory.StartNew(() => {
                while (this.mfIsPolling) {
                    foreach (var tempItem in this.Unit<SwitchRO>()) {
                        tempItem.View();
                    }
                    System.Threading.Thread.Sleep(5);
                }

            }, TaskCreationOptions.LongRunning);

            #endregion
        }

    }
}
